import { _decorator, Canvas, Component, RenderTexture, Sprite, SpriteFrame, UITransform, warnID, Widget } from "cc";

const { ccclass, property, requireComponent } = _decorator;

@ccclass('UIConvertMask')
export class UIConvertMask extends Component {
    private _renderTexture: RenderTexture = null;

    public get renderTexture() {
        return this._renderTexture;
    }

    public intiWithCanvas(canvas: Canvas) {
        const uiTransform = this.addComponent(UITransform);
        const widget = this.node.addComponent(Widget);
        widget.isAlignBottom = true;
        widget.isAlignLeft = true;
        widget.isAlignRight = true;
        widget.isAlignTop = true;
        widget.top = 0;
        widget.left = 0;
        widget.right = 0;
        widget.bottom = 0;
        widget.alignMode = Widget.AlignMode.ON_WINDOW_RESIZE;
        widget.target = canvas.node;
        widget.updateAlignment();

        const sprite = this.node.addComponent(Sprite);
        sprite.sizeMode = Sprite.SizeMode.CUSTOM;
        const renderTexture = new RenderTexture();
        renderTexture.reset({ width: uiTransform.width, height: uiTransform.height });
        renderTexture.addRef();
        const spriteFrame = new SpriteFrame();
        spriteFrame.texture = renderTexture;
        sprite.spriteFrame = spriteFrame;
        this._renderTexture = renderTexture;
    }

    protected onDestroy(): void {
        if (this._renderTexture) {
            this._renderTexture.decRef();
            this._renderTexture = null;
        }
    }
}